<?php

namespace app\admin\service;

use app\common\Message;
use app\model\ConsultBlacklistModel;
use app\model\UserModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Service;

class ExportBlackService extends Service
{
    use Message;

    /**
     * 导出
     * @param $param
     * @return bool
     */
    public function exportBlack($param): bool
    {
        //验证身份
        $isCheckService = new OnlineExportService($this->app);
        $isCheck = $isCheckService->CheckParam($param);
        if(!$isCheck){
            $this->message = $isCheckService->getMessage();
            return false;
        }
        //获取要导出的信息
        $ids = $this->getBlackInfo($param);
        if(!$ids){
            $this->message = $this->getMessage();
            return false;
        }
        //导出excel
        $this->result = [
            'ids' => $ids,
            'url' => $this->ExportBlackList($this->getResult(),$param)
        ];
        return true;
    }

    /**
     * 获取数据
     * @param $param
     */
    public function getBlackInfo($param)
    {
        $where = [];
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
        } else {
            if (!empty($param['start_time'])) {
                $where[] = ['time', '>=', $param['start_time']];
            }
            if (!empty($param['end_time'])) {
                $where[] = ['time', '<=', $param['end_time']];
            }
        }
        if (!empty($param['source'])){
            $where[] = ['source','=',$param['source']];
        }
        if (!empty($param['reason_id'])){
            $where[] = ['reason','in',$param['reason_id']];
        }
        if (!empty($param['duration'])){
            $where[] = ['duration','in',$param['duration']];
        }
        if (!empty($param['consult'])){
            $where[] = ['consult_id','in',$param['consult']];
        }
        if (!empty($param['sex'])) {
            //普通用户的性别筛选
            $UserModel = new UserModel();
            $ids = $UserModel->where('sex', '=', $param['sex'])->column('id');
            if (!empty($ids)) {
                $where[] = ['uid', 'in', $ids];
            } else {
                $where[] = ['id', '=', -1];
            }
        }
        if(!empty($param['department_id'])){
            $UserModel = new UserModel();
            $ids = $UserModel->where('department_id', 'in', $param['department_id'])->column('id');
            if (!empty($ids)) {
                $where[] = ['uid', 'in', $ids];
            } else {
                $where[] = ['id', '=', -1];
            }
        }
        $where[] = ['unit_id','=',$param['unit_id']];
        $ConsultBlacklistModel = new ConsultBlacklistModel();
        $query = $ConsultBlacklistModel->where($where);
        $data = $query
            ->with([
                'user', 'consult'
            ])->order('id desc')->select();
        if(count($data)>0){
            $this->result = $data->toArray();
            return $query->column('id');
        }else{
            $this->message = '暂无数据！';
            return false;
        }
    }

    public function ExportBlackList($param,$data)
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        //设置默认列宽
        $sheet->getDefaultColumnDimension()->setWidth(20);//宽
        $sheet->getRowDimension(1)->setRowHeight(20);//高
        // 设置工作表标题
        $sheet->setTitle('黑名单列表');
        // 设置单元格数据
        $header = [
            'A1' => '用户姓名',
            'B1' => '移入时间',
            'C1' => '移入来源',
            'D1' => '移入黑名单原因',
            'E1' => '负责咨询师',
            'F1' => '黑名单持续时长',
        ];
        // 设置表头样式
        $styleArray = $this->ExcelHeadStyleKey();
        // 填充表头
        foreach ($header as $cell => $value) {
            $sheet->setCellValue($cell,$value);
            $sheet->getStyle($cell)->applyFromArray($styleArray);
        }
        // 设置内容样式
        $styleInfoArray = $this->ExcelInfoStyleKey();
        $black_reason = json_decode($data['black_reason'],true);
        $black_reasons = [];
        foreach($black_reason['data'] as $v){
            $black_reasons[$v['key']] = $v;
        }
        $duration = json_decode($data['blackout_duration'],true);
        $durations = [];
        foreach($duration['data'] as $v){
            $durations[$v['time']] = $v;
        }
        foreach ($param as $key => $item) {
            // 设置单元格数据
            $key = $key + 2;
            $sheet->setCellValue('A' . $key, $item['user_name']);
            $sheet->setCellValue('B' . $key, date('Y-m-d H:i:s',$item['time']));
            $sheet->setCellValue('C' . $key, $item['source'] == 1?'线上咨询':'线下预约');
            $sheet->setCellValue('D' . $key, $black_reasons[$item['reason']]['value']);
            $sheet->setCellValue('E' . $key, $item['consult_name']);
            $sheet->setCellValue('F' . $key, $durations[$item['duration']]['name']);
            $sheet->getStyle(($key))->applyFromArray($styleInfoArray);
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/black_list'.date('Ym').'/'.date('d').'_'.time().uniqid();
        $file_path  = dirname('./public' . $save_name.$ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return oss('./public' . $save_name . $ext, $ext);
    }

    /**
     * 设置表头样式
     * @return array
     */
    public static function ExcelHeadStyleKey(): array
    {
        return [
            'font' => [
                'bold' => true, // 加粗
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, // 水平居中
                'vertical' => Alignment::VERTICAL_CENTER, // 垂直居中
                'wrap' => true, // 自动换行
            ],
        ];
    }

    /**
     * 设置内容样式
     * @return array
     */
    public static function ExcelInfoStyleKey(): array
    {
        return [
            'font' => [
                'bold' => false, // 加粗
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_LEFT, // 水平居左
                'vertical' => Alignment::VERTICAL_CENTER, // 垂直居中
                'wrap' => true, // 自动换行
            ],
        ];
    }
}